package com.lin.musicplayer.Interface;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.lin.musicplayer.MusicFilter;
import com.lin.musicplayer.MusicPlay;
import com.lin.musicplayer.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by crystal on 2016/7/5.
 */
public class LocalMusic extends Activity {
    private MediaPlayer mediaPlayer;
    private LocalMusic localMusic;
    private static final File Music_Path=new File("/sdcard/mp3/");
    public List<String> musiclist;
    ListView listView;
    public String songname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.localmusic);
        mediaPlayer=new MediaPlayer();
        listView=(ListView)findViewById(R.id.list);
        setListAdapter();
        listView.setOnItemClickListener(new ItemClickEvent());

    }
    public LocalMusic()
    {
        musiclist=new ArrayList<String>();
        if(Music_Path.listFiles(new MusicFilter()).length>0)
        {
            for(File file:Music_Path.listFiles(new MusicFilter()))
            {
                musiclist.add(file.getAbsolutePath());
            }
        }
    }
    public void setListAdapter()
    {
        localMusic=new LocalMusic();
        List<Map<String,Object>> date=new ArrayList<Map<String,Object>>();
        for(String path:localMusic.musiclist)
        {
            Map<String,Object>map=new HashMap<String, Object>();
            File file=new File(path);
            map.put("fileName",file.getName());
            date.add(map);
            SimpleAdapter adapter=new SimpleAdapter(this,date,android.R.layout.simple_list_item_2,new String[]{"fileName"},new int[]{android.R.id.text1});
            listView.setAdapter(adapter);
        }
    }
   private final class ItemClickEvent implements AdapterView.OnItemClickListener {

       Map<String,Object>map=new HashMap<String, Object>();
       @Override
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
           map= (Map<String, Object>) listView.getItemAtPosition(i);
           String text= (String) map.get("fileName");
           Intent intent=new Intent();
           Bundle bundle=new Bundle();
           bundle.putString("fileName",text);
           intent.putExtras(bundle);
           intent.setClass(LocalMusic.this,MusicPlay.class);
           startActivity(intent);
       }
   }
    public void setsongname(String dataSource)
    {
        File file=new File(dataSource);
        String name=file.getName();
        int index=name.lastIndexOf(".");
        songname=name.substring(0,index);
    }
}
